package com.zbkj.front.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.zbkj.common.exception.CommonException;
import com.zbkj.common.model.file.PeFile;
import com.zbkj.common.model.file.PeFileType;
import com.zbkj.common.request.file.AdminFileSaveRequest;
import com.zbkj.common.request.file.AdminFileUpdateRequest;
import com.zbkj.common.response.file.AdminFileResponse;
import com.zbkj.common.response.file.AdminFileTypeResponse;
import com.zbkj.common.response.file.FileResponse;
import com.zbkj.common.response.file.FileTypeResponse;
import com.zbkj.front.service.IFileHandleService;
import com.zbkj.service.service.file.IPeFileService;
import com.zbkj.service.service.file.IPeFileTypeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class FileHandleServiceImpl implements IFileHandleService {

    @Autowired
    private IPeFileService peFileService;

    @Autowired
    private IPeFileTypeService peFileTypeService;



    @Override
    public List<FileTypeResponse> fileTypeList() {
        List<FileTypeResponse> returnList = new ArrayList<>();
        List<PeFileType> list = peFileTypeService.lambdaQuery().eq(PeFileType::getDeleteFlag, 0).list();
        if(ObjectUtil.isEmpty(list)){
            return returnList;
        }

        List<Long> fileTypeIds = list.stream().map(PeFileType::getId).collect(Collectors.toList());
        List<PeFile> files = peFileService.lambdaQuery().in(PeFile::getFileType, fileTypeIds)
                .eq(PeFile::getDeleteFlag, 0).list();
        List<FileResponse> fileResponsesList = new ArrayList<>();
        Map<Long, List<FileResponse>> fileTypeGroup = new HashMap<>();
        if(ObjectUtil.isNotEmpty(files)){
            for (PeFile file : files) {
                FileResponse fileResponse = new FileResponse();
                BeanUtils.copyProperties(file,fileResponse);
                fileResponsesList.add(fileResponse);
            }
            fileTypeGroup = fileResponsesList.stream().collect(Collectors.groupingBy(FileResponse::getFileType));
        }

        for (PeFileType peFileType : list) {
            FileTypeResponse fileTypeResponse = new FileTypeResponse();
            BeanUtils.copyProperties(peFileType,fileTypeResponse);
            if(fileTypeGroup.containsKey(peFileType.getId())){
                fileTypeResponse.setFileList(fileTypeGroup.get(peFileType.getId()));
            }
            returnList.add(fileTypeResponse);
        }
        return returnList;
    }


}
